/*
 * Copyright 2010 Peter Backx, streamhead.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 * 
 * The getResponse code was re-used from http://paypal-nvp.sourceforge.net/
 * Thanks for making this code public
 */
package hibari.server.ipn;

import hibari.PMF;
import hibari.client.model.DownloadToken;
import hibari.server.mail.Mailer;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class IPNServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private static final Logger log = Logger.getLogger(IPNServlet.class.getName());

	public IPNServlet() {
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		log.info("IPN received");
		IPNMessage message = new IPNMessageParser(nvp(req), true).parse();

		DownloadToken token = new DownloadToken();
		token.setEmail(message.getPayerEmail());
		token.setIssuedDate(new Date());
		token.setUuid(UUID.randomUUID().toString());
		token.setWeekNumber(Integer.parseInt(message.getItemNumber()));

		PersistenceManager pm = PMF.get().getPersistenceManager();
		pm.makePersistent(message);
		pm.makePersistent(token);
		pm.close();

		Mailer mailer = new Mailer();
		mailer.sendMail(token);

		log.info("parsed message: " + message);
	}

	@SuppressWarnings("unchecked")
	protected Map<String, String> nvp(HttpServletRequest req) {
		Map<String, String[]> params = req.getParameterMap();
		Map<String, String> nvp = new HashMap<String, String>();
		for (Map.Entry<String, String[]> entry : params.entrySet()) {
			String value = "";
			for (int i = 0; i < entry.getValue().length; i++) {
				value += entry.getValue()[i];
				if (i < entry.getValue().length - 1) {
					value += ",";
				}
			}
			nvp.put(entry.getKey(), value);
		}
		return nvp;
	}

}